package com.example.demo.config.recode;

import com.example.demo.service.UserService;
import lombok.Data;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

@Data
public class ReCodeAuthenticationProvider  implements AuthenticationProvider {
    private UserService userService;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        ReCodeAuthenticationToken authenticationToken = (ReCodeAuthenticationToken) authentication;

        WxMpOAuth2AccessToken principal = (WxMpOAuth2AccessToken) authenticationToken.getPrincipal();
        UserDetails user = userService.loadUserByUsername( principal.getOpenId() );

        if (user == null) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }

        ReCodeAuthenticationToken authenticationResult = new ReCodeAuthenticationToken(user, user.getAuthorities());

        authenticationResult.setDetails(authenticationToken.getDetails());
        authenticationResult.setCredentials( authenticationToken.getCredentials() );
        return authenticationResult;
    }


    @Override
    public boolean supports(Class<?> authentication) {
        return ReCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }

}
